import { message } from 'antd';

import api from '../../api';
import _ from 'lodash';

export default {
  namespace: 'workStationM',
  state: {
    adjustArgs: {}, // 持仓交易管理响应模拟组合的一键调仓的参数
    productTableList: [], // 产品组合列表
    portfolioList: [], // 组合下拉列表
    columns: [
      // 持仓列表列
      {
        title: '证券名称',
        dataIndex: 'securitiesName',
        key: 'securitiesName',
        display: true,
        disabled: true,
      },
      {
        title: '证券代码',
        dataIndex: 'securitiesCode',
        key: 'securitiesCode',
        display: true,
        disabled: true,
      },
      {
        title: '持仓数量',
        dataIndex: 'holdingNum',
        key: 'holdingNum',
        display: true,
        disabled: true,
      },
      {
        title: '权重(%)',
        dataIndex: 'holdingWeight',
        key: 'holdingWeight',
        type: 'rate',
        width: 70,
        display: true,
        disabled: true,
      },
      {
        title: '成本价',
        dataIndex: 'radeCost',
        key: 'radeCost',
        display: true,
        type: 'money',
      },
      {
        title: '最新收盘价',
        dataIndex: 'closingPrice',
        key: 'closingPrice',
        display: true,
        type: 'money',
      },
      {
        title: '持仓市值',
        dataIndex: 'marketvalue',
        key: 'marketvalue',
        width: 150,
        display: true,
        type: 'money',
      },
      {
        title: '当日盈亏',
        dataIndex: 'todayProfitAndLoss',
        key: 'todayProfitAndLoss',
        display: false,
        type: 'money',
      },
      {
        title: '总盈亏',
        dataIndex: 'totalProfitAndLoss',
        key: 'totalProfitAndLoss',
        display: true,
        type: 'money',
      },
      {
        title: '总盈亏比例(%)',
        dataIndex: 'totalProfitAndLossRatio',
        key: 'totalProfitAndLossRatio',
        display: false,
        width: '86px',
        render: (text) => {
          if (text === null || text === undefined) {
            return '--';
          }
          // NaN: Not a Number
          // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
          // eslint-disable-next-line no-restricted-globals
          if (isNaN(text)) {
            return text;
          }
          return (Number(text) * 100).toFixed(2);
        },
      },
      {
        title: '当日盈亏比例(%)',
        dataIndex: 'todayProfitAndLossRatio',
        key: 'todayProfitAndLossRatio',
        display: false,
        width: '100px',
        render: (text) => {
          if (text === null || text === undefined) {
            return '--';
          }
          // NaN: Not a Number
          // isNaN()的缺点就在于 null、空格以及空串会被按照0来处理
          // eslint-disable-next-line no-restricted-globals
          if (isNaN(text)) {
            return text;
          }
          return (Number(text) * 100).toFixed(2);
        },
      },
      {
        title: '申万行业',
        dataIndex: 'industry',
        key: 'industry',
        display: false,
      },
      {
        title: '暴露度最大风格因子',
        dataIndex: 'exposedFactor',
        key: 'exposedFactor',
        display: false,
        width: '150px',
      },
    ],
    holdDataSource: {}, // 持仓列表数据
    checkedKeysInfo: ['securitiesName', 'securitiesCode', 'holdingNum', 'holdingWeight', 'radeCost', 'closingPrice', 'marketvalue', 'totalProfitAndLoss'], // 持仓列表选择key
    poolColumns: [
      {
        title: '券池名称',
        dataIndex: 'name',
        key: 'name',
        align: 'left',
        ellipsis: true,
      },
    ],
    poolColumns1: [
      {
        title: '证券代码',
        dataIndex: 'stockCode',
        key: 'stockCode',
      },
      {
        title: '证券名称',
        dataIndex: 'stockName',
        key: 'stockName',
        width: '98px',
        ellipsis: true,
      },
      {
        title: '可投资额度',
        dataIndex: 'investmentAmounts',
        key: 'investmentAmounts',
      },
      {
        title: '交易数量',
        dataIndex: 'amount',
        key: 'amount',
      },
    ],
  },
  effects: {
    *getModeByid({ payload, callback }, { call }) {
      const response = yield call(api.workStation.queryById, payload);
      if (response.code == 0) {
        callback(response.data.dataSource ?? []);
      } else {
        callback(response.data ?? []);
        message.error(response.msg || `获取失败-${api.workStation.stockTable}`);
      }
    },
    // 真实获取持仓管理列表
    *getStockTable({ payload, callback }, { call }) {
      try {
        const response = yield call(api.workStation.stockTable, payload);
        if (response.success) {
          callback(response ?? []);
        } else {
          callback(response ?? []);
          message.error(response.message || `获取失败-${api.workStation.stockTable}`);
        }
      } catch (e) {
        console.log(e);
      }
    },
    *saveCol({ payload, callback }, { call }) {
      try {
        const response = yield call(api.workStation.saveCol, payload);
        callback(response);
      } catch (e) {
        console.log(e);
      }
    },
    // 真实表头
    *queryShowCol({ payload, callback }, { call }) {
      try {
        const response = yield call(api.workStation.queryShowCol, payload);
        if (response.code == 0) {
          callback(response.data.dataSource.columns ?? []);
        } else {
          callback(response.data.dataSource.columns ?? []);
          message.error(response.msg || `获取失败-${api.workStation.queryShowCol}`);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 真实中间的统计信息
    *getSearchReal({ payload, callback }, { call }) {
      try {
        const response = yield call(api.workStation.getSearchTotal, payload);
        if (response.code == 0) {
          callback(response.data ?? {});
        } else {
          callback(response.data ?? {});
          message.error(response.msg || `获取失败-${api.workStation.getSearchTotal}`);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 真实统计表格
    *queryRealList({ payload, callback }, { call }) {
      try {
        const response = yield call(api.workStation.queryRealDate, payload);
        if (response?.success) {
          callback(response.data ?? []);
        } else {
          callback(response?.data ?? []);
          message.error(response?.msg || '查询持仓管理统计表格失败!');
        }
      } catch (e) {
        console.log(e);
        message.error('查询持仓管理统计表格失败');
      }
    },
    // 查询产品组合列表
    *queryProductTableList({ payload, callback }, { call, put }) {
      const response = yield call(api.workStation.queryProductTableList, payload);

      if (response && response.code == 0) {
        const productTableList = [];
        response.data.dataSource?.forEach((item) => {
          productTableList.push({
            value: item.portfolioCode,
            title: item.portfolioName,
            portfolioId: item.portfolioId,
            portfolioType: item.portfolioType,
            performanceBenchmarkId: item.performanceBenchmarkId,
            isBenchmarkFlag: item.isBenchmarkFlag,
          });
        });
        callback(response.data.dataSource);
        yield put({
          type: 'setState',
          payload: {
            productTableList,
            portfolioList: response.data.dataSource || [],
          },
        });
      } else {
        callback();
        message.error(response?.msg || '查询产品组合列表失败！');
      }
    },
    // 查询持仓列表
    *queryHoldData({ payload, callback }, { call, put }) {
      const response = yield call(api.workStation.queryHoldData, payload);

      if (response && response.code == 0) {
        const totalDataSourceForAdjust = _.cloneDeep(response.data.totalDataSource);
        const totalData = [
          // 持仓统计信息列
          {
            name: '类别', // 名称
            key: 'category',
          },
          {
            name: '权重(%)', // 名称
            key: 'weight',
          },
          {
            name: '持仓市值', // 名称
            key: 'positionPrice',
          },
          {
            name: '总盈亏', // 名称
            key: 'totalProfitAndLoss',
          },
          {
            name: '总盈亏比例(%)', // 名称
            key: 'totalProfitAndLossRatio',
          },
        ];
        response.data.totalDataSource.map((item, index) => {
          totalData.map((val) => {
            if (val.key == 'weight') {
              val[`value${index}`] = Math.round(item[val.key] * 10000) / 100;
            } else if (val.key == 'totalProfitAndLossRatio') {
              if (Math.abs(item[val.key] * 100) < 0.01 && item[val.key] != 0) {
                val[`value${index}`] = null;
              } else {
                val[`value${index}`] = item[val.key] * 100;
              }
            } else {
              val[`value${index}`] = item[val.key];
            }
          });
        });
        response.data.totalDataSource = totalData;
        yield put({
          type: 'setState',
          payload: {
            holdDataSource: response.data,
          },
        });
        callback(response.data, totalDataSourceForAdjust);
      } else {
        yield put({
          type: 'setState',
          payload: {
            holdDataSource: {},
          },
        });
        callback();
        message.error(response?.msg || '查询持仓列表失败！');
      }
    },
    // 确定调仓
    *changePosition({ payload, callback }, { call }) {
      const response = yield call(api.workStation.changePosition, payload);

      if (response && response.code == 0) {
        callback(true);
        message.success('调仓成功');
      } else {
        callback();
        message.error(response?.msg || '调仓失败！');
      }
    },
    // 券池导入
    *poolExport({ payload, callback }, { call }) {
      const response = yield call(api.workStation.poolExport, payload);

      if (response && response.code == 0) {
        callback(true);
        message.success('券池导入成功');
      } else {
        callback();
        message.error(response?.msg || '导入失败！');
      }
    },
    // 保存列选择
    *save({ payload }, { put }) {
      yield put({
        type: 'setState',
        payload: {
          columns: payload.columns || [],
          checkedKeysInfo: payload.checkedKeysInfo || [],
        },
      });
    },
    // 持仓模板导入
    *mouldImport({ payload, callback }, { call }) {
      const response = yield call(api.workStation.mouldImport, payload);

      if (response && response.code == 0) {
        callback(true);
        message.success('导入成功');
      } else {
        callback();
        message.error(response?.msg || '导入失败！');
      }
    },
    // 查询交易管理列表
    *queryTransactionData({ payload, callback }, { call }) {
      const response = yield call(api.workStation.queryTransactionData, payload);
      if (response && response.code == 0) {
        callback(response.data);
      } else {
        callback();
        message.error(response?.msg || '查询交易管理列表失败！');
      }
    },

    // 导入交易
    *importTransaction({ payload, callback }, { call }) {
      const response = yield call(api.workStation.importTransaction, payload);

      if (response && response.code == 0) {
        callback(true);
        message.success('导入成功');
      } else {
        callback();
        message.error(response?.msg || '导入失败！');
      }
    },
    // 查询现金管理列表
    *queryCashData({ payload, callback }, { call }) {
      const response = yield call(api.workStation.queryCashData, payload);
      if (response && response.code == 0) {
        callback(response.data);
      } else {
        callback();
        message.error(response?.msg || '查询现金管理列表失败！');
      }
    },
    // 查询现金
    *queryCashData1({ payload, callback }, { call }) {
      const response = yield call(api.workStation.queryCashData, payload);
      if (response && response.code == 0) {
        callback(response.data);
      } else {
        callback();
        message.error(response?.msg || '查询现金失败！');
      }
    },
    // 现金调整
    *adjustCash({ payload, callback }, { call }) {
      const response = yield call(api.workStation.adjustCash, payload);

      if (response && response.code == 0) {
        callback(true);
        message.success('现金调整成功');
      } else {
        callback();
        message.error(response?.msg || '现金调整失败！');
      }
    },
    // 持仓可选时间范围
    *getTradetime({ payload, callback }, { call }) {
      const response = yield call(api.workStation.getTradetime, payload);

      if (response?.code == 0) {
        callback(response.data);
      } else {
        callback();
        message.error(response?.msg || '获取可选时间失败失败！');
      }
    },
    *getLatestPrice({ payload, callback }, { call }) {
      const response = yield call(api.workStation.getPreClosePx, payload);
      if (response.code == 0) {
        callback(response.data?.dataSource[0]);
      } else {
        message.error(response.msg || '查询最新价失败');
      }
    },
  },

  reducers: {
    setState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
